package com.core.shared;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/12/9
 * Time: 15:51
 * To change this template use Editor | File and Code Templates.
 */
public class IPv4Util {

    /**
     * left shifting 24,16,8,0 and bitwise OR
     * 192 << 24
     * 168 << 16
     * 1 << 8
     * 2 << 0
     *
     * @param ipAddress
     * @return
     */
    public static long ipToLong(String ipAddress) {
        if (CommonUtils.isEmpty(ipAddress)) {
            return 0;
        }
        long result = 0;
        String[] ipAddressInArray = ipAddress.split("\\.");
        for (int i = 3; i >= 0; i--) {
            long ip = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ip << (i * 8);
        }
        return result;
    }


    /**
     * long to ip
     *
     * @param i
     * @return
     */
    public static String longToIp(long i) {
        return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
    }

}
